package com.axend.aerosense.dev.viewmodel;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.axend.aerosense.base.impl.IBaseView;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.storage.MmkvHelper;
import com.axend.aerosense.base.viewmodel.CustomBaseViewModel;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.util.JsonUtil;
import com.axend.aerosense.dev.entity.DevHeartArgsBean;
import com.axend.aerosense.dev.entity.DevHeartCalibrateBean;
import com.axend.aerosense.network.EasyHttp;
import com.axend.aerosense.network.cache.model.CacheMode;
import com.axend.aerosense.network.callback.SimpleCallBack;
import com.axend.aerosense.network.exception.ApiException;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.math.BigDecimal;

public class BedCalibrationViewModel extends CustomBaseViewModel<DevHeartArgsBean> {
    private static final double METRE_TO_FOOT = 3.2808;  //米转英尺
    private static final double FOOT_TO_METRE = 0.3048;  //英尺转米

    //    private Handler handler;
    //是否开始校准
    private MutableLiveData<Boolean> isStartCalibrate = new MutableLiveData<>(false);
    //progress的值
    private MutableLiveData<Integer> proNum = new MutableLiveData<>(0);
    //是否校准成功
    private MutableLiveData<Boolean> isCalibrateSuccess = new MutableLiveData<>(false);
    //用户设置的高度值
    private MutableLiveData<Double> devHeight = new MutableLiveData<>(0.0);
    //雷达的安装模式
    private int radarInstallMode = -1;
    //雷达ID
    private String radarId = "";

    public BedCalibrationViewModel(IBaseView baseViewImpl, ILoadDataResult<DevHeartArgsBean> loadDataResultImpl) {
        super(baseViewImpl, loadDataResultImpl);
    }


    public void setRadarId(String radarId) {
        this.radarId = radarId;
    }

    public MutableLiveData<Double> getDevHeight() {
        return devHeight;
    }

    public void setDevHeight(MutableLiveData<Double> devHeight) {
        this.devHeight = devHeight;
    }

    public MutableLiveData<Boolean> getIsCalibrateSuccess() {
        return isCalibrateSuccess;
    }

    public void setIsCalibrateSuccess(MutableLiveData<Boolean> isCalibrateSuccess) {
        this.isCalibrateSuccess = isCalibrateSuccess;
    }

    public MutableLiveData<Integer> getProNum() {
        return proNum;
    }

    public void setProNum(MutableLiveData<Integer> proNum) {
        this.proNum = proNum;
    }

    public MutableLiveData<Boolean> getIsStartCalibrate() {
        return isStartCalibrate;
    }

    public void setIsStartCalibrate(MutableLiveData<Boolean> isStartCalibrate) {
        this.isStartCalibrate = isStartCalibrate;
    }

    @Override
    public void onLoad() {
        //1.http请求雷达设置的高度和安装模式
        EasyHttp.get(UrlApi.getHeartDevArgsUrl + radarId + UrlApi.getPARAMS())
                .headers("token", MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN))
                .cacheMode(CacheMode.NO_CACHE)
                .execute(new SimpleCallBack<DevHeartArgsBean>() {
                    @Override
                    public void onError(ApiException e) {
                        e.printStackTrace();
                        loadDataFail(e.getMessage());
                    }

                    @Override
                    public void onSuccess(DevHeartArgsBean devHeartArgsBean) {
                        getDevHeight().postValue(devHeartArgsBean.getInstallHeight() * METRE_TO_FOOT == 0 ? 3.3 : devHeartArgsBean.getInstallHeight() * METRE_TO_FOOT);
                        radarInstallMode = devHeartArgsBean.getInstallMode() == -1 ? 1 : devHeartArgsBean.getInstallMode();
                        loadDataSuccess(devHeartArgsBean);
                    }

                    @Override
                    public void onTokenExpire() {

                    }
                });
    }

    //请求雷达校准,String radarId,String token
    public void radarCalibrate() {
        float m = (float) (devHeight.getValue() == null ? 1 : devHeight.getValue() * FOOT_TO_METRE);
        BigDecimal bigDecimal = new BigDecimal(m);
        float f2 = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();

        DevHeartCalibrateBean upBean = new DevHeartCalibrateBean(f2, radarInstallMode, radarId);
        final Handler handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (1 == msg.what) {
                    if ((getProNum().getValue() == null ? 1 : getProNum().getValue()) < 99) {
                        getProNum().postValue(getProNum().getValue() + 1);
                        Message message = new Message();
                        message.what = 1;
                        message.arg1 = getProNum().getValue() + 1;
                        this.sendMessageDelayed(message, 200);
                    } else {
                        Message message = new Message();
                        message.what = 2;
                        message.arg1 = 2;
                        this.sendMessage(message);
                    }
                } else if (2 == msg.what) {
                    if ((getProNum().getValue() == null ? 1 : getProNum().getValue()) < 100) {
                        if (1 == msg.arg1 && 1 == msg.arg2) {
                            getProNum().postValue(100);
                            getIsCalibrateSuccess().postValue(true);
                        } else if (2 == msg.arg1 && 1 == msg.arg2) {
                            getProNum().postValue(100);
                            getIsCalibrateSuccess().postValue(false);
                        } else {
                            getProNum().postValue(99);
                            Message message = new Message();
                            message.what = msg.what;
                            message.arg1 = msg.arg1;
                            message.arg2 = 1;
                            this.sendMessageDelayed(message, 100);
                        }
                    }
                }
                super.handleMessage(msg);
            }
        };

        //2.http上传雷达安装高度和模式，请求校准
        EasyHttp.post(UrlApi.URL.OpenDeviceCalibration.getUrl())
                .headers("token", MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN))
                .cacheMode(CacheMode.NO_CACHE)
                .upJson(JsonUtil.toJson(upBean))
                .execute(new SimpleCallBack<Boolean>() {
                    @Override
                    public void onError(ApiException e) {
                        e.printStackTrace();
                        Message message = new Message();
                        message.what = 2;
                        message.arg1 = 2;
                        handler.sendMessage(message);
                        ToastUtils.showShort(e.getMessage());
                        loadDataFail(e.getMessage());
                    }

                    @Override
                    public void onSuccess(Boolean b) {
                        LogUtils.d("BaseStringBean:", b);
                        Message message = new Message();
                        message.what = 2;
                        if (b) {
                            message.arg1 = 1;
                        } else {
                            message.arg1 = 2;
                        }
                        handler.sendMessage(message);
                    }

                    @Override
                    public void onTokenExpire() {

                    }
                });

        Message msg = new Message();
        msg.what = 1;
        msg.arg1 = 1;
        handler.sendMessage(msg);

    }

}
